import React, { useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import rehypeRaw from "rehype-raw";
import rehypeSanitize from "rehype-sanitize";
import CodeBlock from "./CodeBlock";
import ImagePreview from "./ImagePreview";

interface MarkdownRendererProps {
  content: string;
  allowHtml?: boolean;
}

/**
 * Markdown渲染组件
 *
 * 将Markdown文本渲染为React组件
 * 支持GitHub风格的Markdown (GFM)
 * 支持代码高亮
 * 支持可选的HTML渲染（需谨慎使用）
 */
export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
  content,
  allowHtml = false,
}) => {
  // 图片预览状态
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const [isPreviewOpen, setIsPreviewOpen] = useState(false);

  if (!content) return null;

  // 打开图片预览
  const openImagePreview = (imageUrl: string) => {
    setPreviewImage(imageUrl);
    setIsPreviewOpen(true);
  };

  // 关闭图片预览
  const closeImagePreview = () => {
    setIsPreviewOpen(false);
    // 延迟清除图片URL，以便动画完成
    setTimeout(() => setPreviewImage(null), 300);
  };

  // 检查是否为特殊图片，基于alt文本而不是URL
  const isSpecialImage = (alt: string | undefined): boolean => {
    if (!alt) return false;

    // 检查alt文本是否为"file"或包含特定模式
    return (
      alt === "file" ||
      /^file(\d+)?$/.test(alt) || // 匹配 "file", "file1", "file2" 等
      alt.toLowerCase().includes("file:") ||
      alt.toLowerCase().startsWith("cirno:")
    );
  };

  // 获取图片来源标识，根据alt或URL判断
  const getImageSource = (
    alt: string | undefined,
    src: string
  ): { tag: string; style: string } => {
    if (isSpecialImage(alt)) {
      return {
        tag: "Cirno",
        style:
          "bg-gradient-to-r from-purple-400/30 to-pink-400/30 dark:from-purple-600/20 dark:to-pink-600/20",
      };
    }

    // 检查URL中的特定模式，作为备用
    if (src.includes("cirno-1308416229.cos.ap-chengdu.myqcloud.com")) {
      return {
        tag: "Cirno",
        style:
          "bg-gradient-to-r from-purple-400/30 to-pink-400/30 dark:from-purple-600/20 dark:to-pink-600/20",
      };
    }

    // 根据其他URL特征可添加更多来源识别

    // 默认风格
    return {
      tag: "",
      style:
        "bg-gradient-to-r from-blue-300/30 to-purple-300/30 dark:from-blue-500/20 dark:to-purple-500/20",
    };
  };

  const rehypePlugins = allowHtml
    ? [rehypeRaw, rehypeSanitize]
    : [rehypeSanitize];

  return (
    <>
      <ReactMarkdown
        remarkPlugins={[remarkGfm]}
        rehypePlugins={rehypePlugins}
        components={{
          // ReactMarkdown的类型定义有问题，但实际上这些props是可用的
          code: ({ className, children, ...props }) => {
            // 检查是否为内联代码
            const isInline = !className || !/language-(\w+)/.test(className);

            // 内联代码不使用CodeBlock组件
            if (isInline) {
              return (
                <code className={className} {...props}>
                  {children}
                </code>
              );
            }

            // 提取语言信息
            const match = /language-(\w+)/.exec(className || "");
            const language = match ? match[1] : "text";
            const value = String(children).replace(/\n$/, "");

            // 使用自定义CodeBlock组件
            return (
              <CodeBlock
                language={language}
                value={value}
                className={className}
              />
            );
          },
          // 自定义图片渲染，支持点击预览
          img: ({ src, alt, ...props }) => {
            if (!src) return null;

            // 判断图片类型并获取样式
            const { tag, style } = getImageSource(alt, src);
            const isSpecialImg = tag !== "";

            return (
              <div
                className={`my-2 inline-block ${
                  isSpecialImg ? `${tag.toLowerCase()}-image-container` : ""
                }`}
              >
                <div
                  className={`p-[2px] rounded-xl ${style} backdrop-blur-sm shadow-lg hover:shadow-xl transition-all inline-block cursor-pointer`}
                  onClick={() => openImagePreview(src)}
                >
                  <div className="relative overflow-hidden rounded-[10px] bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm">
                    <img
                      src={src}
                      alt={alt || (isSpecialImg ? `${tag}服务器图片` : "图片")}
                      className={`${
                        isSpecialImg
                          ? "max-h-[400px] max-w-full object-contain hover:scale-[1.02] transition-transform duration-300"
                          : "max-h-96 max-w-full object-contain hover:scale-[1.02] transition-transform duration-300"
                      }`}
                      loading="lazy"
                      {...props}
                    />
                    {/* 放大图标 */}
                    <div className="absolute bottom-3 right-3 p-2 rounded-full bg-white/25 dark:bg-black/40 text-gray-700 dark:text-white backdrop-blur-md transform scale-0 group-hover:scale-100 transition-transform duration-300 shadow-lg">
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        className="h-5 w-5"
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                        />
                      </svg>
                    </div>
                    {/* 特殊图片标识 */}
                    {isSpecialImg && (
                      <div className="absolute top-3 left-3 px-2 py-1 rounded-full bg-purple-500/70 dark:bg-purple-600/70 text-white text-xs backdrop-blur-md shadow-lg">
                        {tag}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            );
          },
          // 自定义链接，在新标签页打开
          a: (props) => (
            <a target="_blank" rel="noopener noreferrer" {...props} />
          ),
          // 改进表格样式，减少标题和表格之间的间距
          table: (props) => (
            <div className="table-container my-2">
              <table
                className="min-w-full divide-y divide-gray-300 dark:divide-gray-700"
                {...props}
              />
            </div>
          ),
          thead: (props) => (
            <thead className="bg-gray-50 dark:bg-gray-800" {...props} />
          ),
          tbody: (props) => (
            <tbody
              className="divide-y divide-gray-200 dark:divide-gray-800"
              {...props}
            />
          ),
          tr: (props) => (
            <tr
              className="hover:bg-gray-50 dark:hover:bg-gray-800/50"
              {...props}
            />
          ),
          th: (props) => (
            <th
              className="px-3 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider"
              {...props}
            />
          ),
          td: (props) => <td className="px-3 py-2 text-sm" {...props} />,
          // 减少标题下方的间距
          h1: (props) => <h1 className="mb-2" {...props} />,
          h2: (props) => <h2 className="mb-2" {...props} />,
          h3: (props) => <h3 className="mb-2" {...props} />,
          h4: (props) => <h4 className="mb-2" {...props} />,
          h5: (props) => <h5 className="mb-2" {...props} />,
          h6: (props) => <h6 className="mb-2" {...props} />,
          // 调整段落间距
          p: (props) => <p className="my-1" {...props} />,
        }}
      >
        {content}
      </ReactMarkdown>

      {/* 图片预览组件 */}
      {previewImage && (
        <ImagePreview
          imageUrl={previewImage}
          onClose={closeImagePreview}
          isOpen={isPreviewOpen}
        />
      )}
    </>
  );
};

export default MarkdownRenderer;
